<template>
   <!-- 用户管理 -->
   <div class="permission-user-container">
      <h1 class="page-title">{{ pageTitle }}</h1>

      <el-card class="search-card">
         <div class="search-container">
            <div class="search-form">
               <!-- 基础搜索项始终显示 -->

               <!-- 高级搜索项 -->
               <div
                  class="advanced-search"
                  :class="{ expanded: isExpanded }"
               >
                  <el-row :gutter="20">
                     <el-col :span="4">
                        <el-input
                           v-model="pageData.username"
                           placeholder="请输入用户名"
                           clearable
                        />
                     </el-col>
                     <el-col :span="4">
                        <el-input
                           v-model="pageData.nickname"
                           placeholder="请输入用户昵称"
                           clearable
                        />
                     </el-col>
                     <el-col :span="4">
                        <el-input
                           v-model="pageData.mobile"
                           placeholder="请输入手机号"
                           clearable
                        />
                     </el-col>
                     <el-col :span="4">
                        <el-select
                           v-model="pageData.role_id"
                           placeholder="请选择角色"
                           filterable
                           clearable
                           style="width: 100%"
                        >
                           <el-option
                              v-for="item in tableList"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                           />
                        </el-select>
                     </el-col>
                     <el-col :span="4">
                        <el-select
                           v-model="pageData.status"
                           placeholder="请选择状态"
                           filterable
                           clearable
                           style="width: 100%"
                        >
                           <el-option
                              v-for="item in servicestats"
                              :key="item.table"
                              :label="item.value"
                              :value="item.table"
                           ></el-option>
                        </el-select>
                     </el-col>
                  </el-row>
               </div>
            </div>
            <div style="height: 5px"></div>
            <div class="operation-buttons">
               <div
                  class="filter-toggle"
                  @click="toggleExpand"
               >
                  <img
                     class="filter-icon"
                     :class="{ rotate: isExpanded }"
                     src="@/assets/sx.png"
                     alt="筛选"
                  />
                  <span>{{ isExpanded ? "收起筛选" : "高级筛选" }}</span>
               </div>

               <div class="action-buttons">
                  <el-button
                     type="primary"
                     @click="AddGiftPack"
                     >添加用户</el-button
                  >
                  <el-button
                     type="primary"
                     @click="handleResetPassword"
                     >密码重置</el-button
                  >
                  <el-button
                     plain
                     :icon="RefreshRight"
                     @click="refresh"
                     >刷新</el-button
                  >
               </div>
            </div>
         </div>
      </el-card>
   </div>

   <el-card>
      <el-table
         :data="tableData"
         style="width: 100%"
         stripe
         fit
         @selection-change="handleSelectionChange"
      >
         <el-table-column
            type="selection"
            width="55"
         />
         <el-table-column
            prop="username"
            label="登陆账号"
            width="auto"
         ></el-table-column>
         <el-table-column
            prop="nickname"
            label="姓名"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="编号"
            prop="member_num"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="手机号"
            prop="member_mobile"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="直属组织"
            prop="member_org_name"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="协助组织"
            prop="member_org_names"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="角色组"
            prop="role_name"
            width="auto"
         ></el-table-column>
         <el-table-column
            label="状态"
            prop="status"
            width="auto"
         >
            <template #default="scope">
               <el-switch
                  v-model="scope.row.status"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="启用"
                  inactive-text="禁用"
                  @click="isCheck(scope.row)"
               />
            </template>
         </el-table-column>
         <el-table-column
            label="操作"
            fixed="right"
            width="200"
         >
            <template #default="scope">
               <el-button
                  size="text"
                  @click="handleupdate(scope.row)"
                  >编辑</el-button
               >
               <el-button
                  size="text"
                  @click="handleViews(scope.row)"
                  >查看权限</el-button
               >
            </template>
         </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
         @pageSize="pageSize"
         @getPage="getPage"
         :page="pageData.page"
         :page-size="pageData.pageSize"
         :total="total"
      />
   </el-card>
   <viewPermissionPopup ref="viewPermissionPopupRef" />
   <permissionUserAdd
      ref="AddPackRef"
      @init="init"
   />
</template>

<script setup>
   import api from "@/api/index.js";
   import CardTitle from "@/components/card-title/CardTitle.vue";
   const showBackButton = false; // 更改为 `false` 表示不需要返回按钮
   const pageTitle = "用户权限管理"; // 更改为你需要的标题
   import Pagination from "@/components/Pagination.vue";
   import { watchThrottled } from "@vueuse/core";
   import { onMounted, ref, watch } from "vue";
   import { ElMessage, ElMessageBox } from "element-plus";
   import { RefreshRight } from "@element-plus/icons-vue";
   import permissionUserAdd from "./permissionUser/permissionUserAdd.vue";
   import viewPermissionPopup from "./permissionUser/viewPermissionPopup.vue";
   const detailsActionRef = ref(null);
   const AddPackRef = ref(null);
   const viewPermissionPopupRef = ref(null);
   const total = ref(0);
   const tableData = ref([]);
   const order_scope = ref([
      { value: "正式订单", table: "1" },
      { value: "测试订单", table: "2" },
   ]);
   const nub = ref(0);
   const servicestats = ref([
      { value: "启用", table: "1" },
      { value: "禁用", table: "0" },
   ]);
   // 日期的双向绑定去
   const selectedDates = ref([]);
   const pageData = ref({
      page_size: 10, // 每页显示条数
      page: 1, // 当前页码
      username: "", // 用户名
      mobile: "", // 手机号
      role_id: "", // 角色ID
      status: "", // 状态
   });

   // 监听 selectedDates 的变化
   watch(selectedDates, (newVal) => {
      if (!newVal || newVal.length === 0) {
         pageData.value.start_datetime = "";
         pageData.value.end_datetime = "";
         init(); // 当 selectedDates 为空时重新加载数据
      }
   });

   // 侦听动态分页
   watchThrottled(
      pageData.value,
      (val) => {
         console.log(val);
         Object.keys(val).forEach((key) => {
            if (val[key] == null || val[key] == undefined) {
               val[key] = "";
            }
         });
         init(); //获取表格数据的方法
      },
      { throttle: 1000, deep: true }
   );

   // 刷新
   const refresh = async () => {
      ElMessage.success("正在刷新数据...");
      await init();
      ElMessage.success("数据刷新成功");
   };
   // 切换状态
   const isCheck = async (row) => {
      ElMessageBox.confirm(row.status == 0 ? "确定要禁用吗？" : "确定要启用吗？", "提示", {
         confirmButtonText: "确定",
         cancelButtonText: "取消",
         type: "warning",
      })
         .then(() => {
            ElMessage({
               type: "success",
               message: row.status == 0 ? "禁用成功" : "启用成功",
            });
            changeStatus(row);
         })
         .catch(() => {
            ElMessage({
               type: "info",
               message: "取消切换",
            });
            init();
         });
   };
   const ids = ref([]);
   // 多选
   const handleSelectionChange = (selection) => {
      ids.value = selection.map((item) => item.id);
   };
   // 重置密码
   const handleResetPassword = async (row) => {
      if (ids.value.length === 0) {
         ElMessage.error("请至少选择用户");
         return;
      }
      console.log({ id: ids.value }, "666");

      ElMessageBox.confirm("确定要重置密码吗？", "提示", {
         confirmButtonText: "确定",
         cancelButtonText: "取消",
         type: "warning",
      })
         .then(() => {
            api.authority.resetPassword({ ids: JSON.stringify(ids.value) }).then((res) => {
               if (res.code == 200) {
                  ElMessage.success("密码重置成功");
                  init();
               } else {
                  ElMessage.error(res.msg);
               }
            });
         })
         .catch(() => {
            ElMessage.error("取消重置");
         });
   };
   const changeStatus = async (row) => {
      // 保存原始状态值（切换前的状态值是相反的）
      const originalStatus = row.status === 1 ? 0 : 1;

      try {
         const res = await api.authority.editUser({
            id: row.id,
            status: row.status,
         });

         if (res.code == 200) {
            ElMessage.success("状态切换成功");
            // 刷新表格数据
            init();
         } else {
            // 切换失败时，强制将开关状态设置回原来的值
            row.status = originalStatus;
            ElMessage.error("状态切换失败");
            // 强制刷新UI以确保开关状态正确显示
            tableData.value = [...tableData.value];
         }
      } catch (error) {
         // 发生异常时也要回退状态
         row.status = originalStatus;
         ElMessage.error("状态切换出错");
         tableData.value = [...tableData.value];
      }
   };
   // 打开查看弹窗
   const handleViews = (data) => {
      viewPermissionPopupRef.value.openDialog(data);
   };

   // 打开添加用户弹窗
   const AddGiftPack = () => {
      AddPackRef.value.handleDialog();
   };
   const userInfo = ref({});
   // 点击编辑弹窗
   const handleupdate = (row) => {
      AddPackRef.value.handleDialog(row);
   };

   // 获取用户列表
   const init = async () => {
      let _a = Object.keys(pageData.value).reduce((acc, key) => {
         if (pageData.value[key] !== "" && pageData.value[key] !== null && pageData.value[key] !== undefined) {
            acc[key] = String(pageData.value[key]);
         }
         return acc;
      }, {}); // 这里添加了一个空对象作为初始值
      console.log(_a);
      const res = await api.authority.getUserList({
         ..._a,
      });
      if (res.code === 200) {
         tableData.value = res.data.data;
         total.value = res.data.pager.total_records;
      }
   };
   const tableList = ref([]);
   // 获取角色列表
   const getRoleList = async () => {
      try {
         const res = await api.authority.getRoleList();
         if (res.code === 200) {
            // 方案1：强制转换为数组
            const data = Array.isArray(res.data) ? res.data : [];
            tableList.value = data.map((item) => ({
               id: item.id,
               name: item.name,
            }));
         } else {
            ElMessage.error(res.msg || "获取角色列表失败");
         }
      } catch (error) {
         console.error("获取角色列表失败:", error);
         ElMessage.error("获取角色列表失败");
      }
   };
   const pageSize = (e) => {
      pageData.value.page_size = e;
   };
   const getPage = (e) => {
      pageData.value.page = e;
   };

   const handleSearch = () => {
      pageData.value.page = 1; // 重置页码
      init();
   };

   // 添加展开收起状态控制
   const isExpanded = ref(false);

   const toggleExpand = () => {
      isExpanded.value = !isExpanded.value;
   };

   onMounted(() => {
      init();
      getRoleList();
   });
</script>

<style lang="scss" scoped>
   :deep(.el-card__body) {
      padding: 5px;
   }
   .permission-user-container {
      width: 100%;
      .page-title {
         font-size: 20px;
         font-weight: 600;
         margin-bottom: 20px;
         color: #333;
      }

      .search-container {
         .search-form {
            .advanced-search {
               max-height: 0;
               overflow: hidden;
               transition: max-height 0.3s ease-in-out;
               margin-top: 0;
               transition: all 0.3s ease;

               &.expanded {
                  max-height: 500px;
                  margin-top: 20px;
               }
            }
         }
      }

      .operation-buttons {
         display: flex;
         justify-content: space-between;
         align-items: center;

         .filter-toggle {
            display: flex;
            align-items: center;
            cursor: pointer;
            color: #606266;

            .filter-icon {
               width: 16px;
               height: 16px;
               margin-right: 8px;
               transition: transform 0.3s ease;

               &.rotate {
                  transform: rotate(180deg);
               }
            }

            &:hover {
               color: #409eff;
            }
         }

         .action-buttons {
            display: flex;
            gap: 12px;

            .el-button {
               margin: 0;
            }
         }
      }
   }

   :deep(.el-input__wrapper) {
      background-color: #fafcfb;
   }

   :deep(.el-button--primary) {
      background-color: #6860ff;
      border-color: #6860ff;

      &:hover,
      &:focus {
         background-color: #7d77ff;
         border-color: #7d77ff;
      }
   }

   :deep(.el-button--default) {
      &:hover {
         color: #6860ff;
         border-color: #6860ff;
         background-color: #e2e4fd;
      }
   }

   :deep(.el-input__wrapper:hover) {
      box-shadow: 0 0 0 1px #6860ff inset;
   }
   //分页样式
   .pagination {
      width: calc(100% - 250px);
      position: fixed;
      bottom: 20px;
      right: 20px;
      padding-top: 10px;
      border-top: 1px solid #98989848;
   }

   :deep(.el-pagination.is-background .el-pager li.is-active) {
      background-color: #000 !important;
   }
</style>
